<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/17
 * Time: 14:08
 */
namespace app\admin\controller;

use \think\Controller;
use think\Request;
use think\Db;

class Common extends Controller
{
    protected function _initialize()
    {
        //注册异常处理
        set_exception_handler("admin_exception_handler");

        //开启数据库事务
        Db::startTrans();

        $noLoginList = ['PayNotify','PayNotify2','TimePlan'];
        $controller = request()->controller();
        if(!in_array($controller,$noLoginList)){
            ///检测管理员是否登录
            $this->checkAdmin();
            //验证角色权限
            $this->checkAdminAuthority();
        }
        //获取最近一小时聊天记录
        $list = db("message")->order("id asc")->select();
        $data = [];
        foreach ($list as $item) {
            $uid = $item["send_id"] != 0 ?$item["send_id"]: $item["receive_id"];
            if (isset($data[$uid])) {
                $data[$uid]["last_id"] = $item["id"];
            } else {
                $user = \app\common\model\User::exists($uid);
                $data[$uid] = [
                    "user_id" => $uid,
                    "nick_name" => $user["nick_name"],
                    "status" => 0,
                    "last_id" => $item["id"],
                    "origin_id" => $item["id"]
                ];
            }
        }
        $this->assign("data_list", $data);
    }

    public function __destruct()
    {
        global $admin_has_exception;

        //根据是否发生异常，决定事务是提交还是回滚
        $admin_has_exception ? Db::rollback() : Db::commit();
        // TODO: Implement __destruct() method.
    }

    /**
     * 模板标题
     * @param string $title
     */
    protected function templateTitle($title = "")
    {
        $this->assign("templateTitle", $title);
    }

    /**
     * 使用模态框布局
     */
    protected function layoutModal()
    {
        $this->view->engine->layout("public/modalLayout");
    }

    /**
     * ajax成功信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxSuccess($info = "", $extra = array())
    {
        $result = array(
            "status"=>0,
            "info" => $info,
            "data" => $extra,
        );
        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * ajax失败信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxError($info = "", $extra = array())
    {
        $result = array(
            "status"=>1,
            "info" => $info,
            "data" => $extra,
        );

        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 渲染地区选择器
     *
     * @param string $regionId 地区ID
     */
    protected function renderRegion($regionId)
    {
        //获取地区
        $region = Db::name("region")
            ->where("id", $regionId)
            ->find();

        //进行渲染
        if ($region)
        {
            $regionList = explode("-", $region["id_path"]);

            //省份
            if ($region["level"] >= 1)
            {
                $this->assign("area_province", $regionList[1]);
            }

            //市
            if ($region["level"] >= 2)
            {
                $this->assign("area_city", $regionList[2]);
            }

            //县区
            if ($region["level"] == 3)
            {
                $this->assign("area_county", $regionList[3]);
            }
        }
    }

    //检测管理员是否登录
    private function checkAdmin()
    {
        if (!session("?H_ADMIN_LOGIN_USER") || session("H_ADMIN_DUE_TIME") < time())
        {
            session("H_ADMIN_REFERER", url("Index/index"));
//            if (strtolower(request()->controller()) === "login")
//            {
//                session("H_ADMIN_REFERER", url("Index/index"));
//            }
//            else
//            {
//                $controller = request()->controller();
//
//                session("H_ADMIN_REFERER", url($controller . "/index"));
//            }

            //判断是否为ajax操作
            if (request()->isAjax())
            {
                die(json_encode(array("status"=>-1,"url"=>url("Login/index"))));
            }
            else
            {
                die("<script>if (window.parent){window.parent.location.href='"
                    . url("Login/index") . "';}else{location.href='"
                    . url("Login/index") . "';}</script>");
            }
        }

        //渲染管理员信息
        $this->assign("current_admin", session("H_ADMIN_LOGIN_USER"));
    }

    //检测管理员权限
    private function checkAdminAuthority()
    {
        //操作
        $operation = request()->controller() . "." . request()->action();

        //当前管理员
        $admin = session("H_ADMIN_LOGIN_USER");

        //如果是超级管理员，则不做任何处理
        if ($admin["is_root"])
        {
            return;
        }
        //获取一级操作
        $action1 = explode('.', $operation)[0];

        // 是否具有所有权限
        //$auth = in_array($action1 . '.*', $admin['authority']);
        // 是否具有指定权限
        foreach ($admin["authority"] as &$sdfasdfasdf){
            $sdfasdfasdf = strtolower($sdfasdfasdf);
        }
//        print_r($admin["authority"]);
//        die();
        $auth =  in_array(strtolower($operation), $admin['authority']);
        // 是否为首页
        $auth = $auth || ($operation == 'Index.index')|| ($operation == 'Chat.send_msg')|| ($operation == 'Chat.getstatus')|| ($operation == 'Chat.getchatlist');
        if (!$auth)
        {
            if (request()->isAjax())
            {
                $this->ajaxError('您的角色无相关权限！');
            }
            else
            {
                $this->error('您的角色无相关权限！');
            }
        }
    }

    /**
     * 当前管理员的ID
     *
     * @return mixed
     */
    protected function currentAdminId()
    {
        //当前管理员
        $admin = session("H_ADMIN_LOGIN_USER");

        return $admin["id"];
    }

}